<template>
    <div>
        <!-- 警告 -->
        <el-alert
            title="注意：只允许为第三级分类设置相关参数！"
            type="warning"
            show-icon
            :closable="false">
        </el-alert>
        <!-- 选择商品分类 -->
        <span>选择商品分类：</span>
        <el-cascader
            v-model="pid"
            :options="categories"
            :props="{ value:'cat_id',label:'cat_name',expandTrigger: 'hover' }"
            @change="getAttributeList"
           >
            </el-cascader>
            <el-tabs v-model="activeName" @tab-click="getAttributeList">
                <el-tab-pane 
                v-for="(item,key) in tabs" 
                :key="key" 
                :label="item.title1+item.title" 
                :name="key">
                </el-tab-pane>
            </el-tabs>
            <!-- 添加按钮 -->
            <el-button @click="
                 model={};
                 $refs.d.show()" 
                 :disabled="!catId" 
                 size="mini" 
                 type="primary">
                    添加{{activeTab.title}}
                 </el-button>
                 <!-- 表格 -->
            <MyTable
                  rowKey="attr_id"
                  :cols="cols" 
                  :data="list" 
                  :loading="queryLoading"
                  >
                  <!-- 标签  -->
                  <template v-slot:expand="{row}">
                    <el-tag
                    :key="index"
                    v-for="(tag,index) in row.tags"
                    closable
                    @close="deleteTag(row,index)">
                    {{tag}}
                    </el-tag>
                    <el-input
                    class="input"
                    autofocus
                    @blur="updateAttrValues(row)"
                    @keyup.enter.native="updateAttrValues(row)"
                    v-model="row.value"
                    v-if="row.visible"
                    :ref="'input'+row.attr_id"
                    size="small"
                    >
                    </el-input>
                    <el-button
                      v-else
                      size="small" 
                      @click="show(row)"
                      >+ New Tag</el-button>

                  </template>
                  <template v-slot:action="{row}">
                       <el-button
                        class="el-icon-edit" 
                        type="primary" size="mini" 
                        @click="
                        model={...row};
                        $refs.d.show()
                        " >编辑</el-button>
                       <el-button
                        class="el-icon-delete-solid" 
                        type="danger" 
                        size="mini"
                        @click="delAttribute(row)" 
                        >删除</el-button>
                  </template>
            </MyTable>
                 <!-- 添加修改 -->
            <DF 
                 lw="80px"
                 :title="title+activeTab.title1+activeTab.title" 
                 :opts="opts" 
                 v-model="model" 
                 ref="d"
                @confirm="confirm">
            </DF>
    </div>
</template>

<script>
import {deleteAttributes,updateAttributes,addAttributes,getCategories,getAttributes} from "api/goods";
    export default {
        name:"params",
        data() {
            return {
                
                /**
                 *  模型
                 */
                model:{},
                /**
                 * 激活的名称
                 */
                activeName:"many",
                /**
                 * 分类id
                 */
                paramsId: [],
                /**
                 * 商品分类
                 */
                categories:[],
                /**
                 * 标签页
                 */
                tabs:{
                    many:{
                        title:"参数",
                        title1:"动态",
                    },
                    only:{
                        title:"属性",
                        title1:"静态",
                    }
                },
            }
        },
        created () {
            const pid=this.pid;
            console.log(pid);
            this.pid="66666666"
            this.getCateogryList();
        },
      computed: {
        /**
         * 属性id
         */
        pid:{
           set(value){
              this.paramsId=value.length<3?[]:value;
           },
           get(){

              return this.paramsId;
           },
        },
        /**
         * 标题
         */
        title(){
          return this.model.attr_id?"修改":"添加";
        },
        /**
         * 表单配置项
         */
        opts(){
            return{
                attr_name:{
                title:this.activeTab.title1+this.activeTab.title,
                required:true,
                max:20,
              }
           }
        },
        /**
         * 分类id
         */
        catId(){
           return this.paramsId.length >3?undefined:this.paramsId.slice(-1)[0];
        },
        /**
         * 激活的标签项
         */
        activeTab(){
            return this.tabs[this.activeName];
        },
        /**
         * 列
         */
        cols() {
           return [
              {
                title:"",
                type:"expand",
                slot:"expand",
              },
              {
                title:"#",
                type:'index',
              },
              {
                title:this.activeTab.title+"名称",
                name:"attr_name",
              },
              {
                title:'操作',
                slot:"action",
                align:"center",
                width:300,
              },
           ]
        }
      },
        methods: {
            /**
             * 删除标签
             */
            async deleteTag(row,index){
               try {
                   row.tags.splice(index,1);
                   row.attr_vals=row.tags.join(" ");
                   await updateAttributes(this.catId,row);
                   this.$m.success("删除成功");
                   this.getAttributeList();
               } catch (error) {}
            },
            /**
             * 更新属性的value值
             */
            async updateAttrValues(row){
                if(!row.value.trim()){
                    return (row.visible=false);
                }
               try {
                   row.attr_vals=row.tags.join(" ")+" "+row.value;
                   await updateAttributes(this.catId,row);
                   this.$m.success("添加成功");
                   this.getAttributeList();
                   row.value="";
                   row.visible=false;
               } catch (error) {
                
               }
            },
            /**
             * 显示输入框
             */
            show(row){
               row.visible=true;
               this.$nextTick(()=>{
                  this.$refs['input'+row.attr_id].focus();
               });
            },
            /**
             * 删除属性
             */
            async delAttribute({attr_name,attr_id}){
                let res;
               try {
                 res= await this.$myConfirm(`你确定要删除【${attr_name}】吗？`);
                 await deleteAttributes(this.catId,attr_id);
                 this.$m.success('删除成功');
                 this.getAttributeList()
               } catch (error) {}
               res&&res();
            },
            /**
             * 提交
             */
            async confirm(){
                const d=this.$refs.d;
               try {
                d.start();
                   await (this.model.attr_id?updateAttributes:addAttributes)(
                    this.catId,
                    {
                        ...this.model,
                        attr_sel:this.activeName,
                    }
                   );
                   this.$m.success(this.title+"成功");
                   this.getAttributeList();
                   d.hide();
               } catch (error) {}
               d.stop();
            },
            /**
             * 获取参数列表
             */
            async getAttributeList(){
                try {
                   if(!this.catId){
                       return this.list.splice(0,Infinity);
                   }
                   this.queryLoading=true;
                   const list=await getAttributes(this.catId,this.activeName);
                  //截取  
                  list.forEach((item)=>{
                      item.tags= item.attr_vals.split(" ").filter((c)=>c);
                      item.value="";
                      item.visible=false;
                  });
                  this.list=list;
                } catch (error) {}
                   this.queryLoading=false;
            },
            /**
             * 获取分类列表
             */
            async getCateogryList() {
                try {
                    
                    this.categories=await getCategories();
                } catch (error) {}
            }
        },
    }
</script>

<style lang="scss" scoped>
.el-alert{
    margin-bottom: 10px;
}
.input{
    width: 100px;
}
</style>